package com.atnjupt.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

/**
 * @author Wizarder
 * @create 2021-06-15 12:09
 */
public class AdminFilter implements Filter {
    public AdminFilter(){
        System.out.println("这是AdminFilter构造器");
    }
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("这是AdminFilter的 init(FilterConfig filterConfig)");
        // 1、获取 Filter 的名称 filter-name 的内容
        System.out.println("filter-name:" + filterConfig.getFilterName());
        // 2、获取在 web.xml 中配置的 init-param 初始化参数
        System.out.println("filter中的init-param:" + filterConfig.getInitParameter("username"));
        System.out.println("filter中的init-param:" + filterConfig.getInitParameter("url"));
        //// 3、获取 ServletContext 对象
        System.out.println("filter获取servletContext对象：" + filterConfig.getServletContext());
    }

    /**
     * 实现请求拦截
     * @param servletRequest
     * @param servletResponse
     * @param filterChain
     * @throws IOException
     * @throws ServletException
     */
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("这是AdminFilter的doFilter");
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;
        Object user = httpServletRequest.getSession().getAttribute("user");
        // 如果等于 null，说明还没有登录
        if(user == null){
            httpServletRequest.getRequestDispatcher("/login.jsp").forward(servletRequest,servletResponse);
            return;
        }else{
            // 让程序继续往下访问用户的目标资源  这一步很重要，不写会无法显示访问的内容！！！
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {
        System.out.println("这是AdminFilter的destroy");
    }
}
